import cgi
import os

from TopicDao import *
from admin import *
from EditTopic import *
from RestUrl import *

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    def get(self):
        topicDao = TopicDao()
        topics = topicDao.loadAll()
        
        if users.get_current_user():
            isAdmin = users.is_current_user_admin()
        else:
            isAdmin = False

        template_values = {'topics': topics,
                           'isAdmin': isAdmin,
                           }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class AddTopic(webapp.RequestHandler):
    def post(self):
        newTopic = Topic()
        
        newTopic.content = self.request.get('content')
        newTopic.score = 0
       
        newTopic.put()
        self.redirect('/')
        
class RestAddTopic(webapp.RequestHandler):
    def get(self):
        newTopic = Topic()
        
        newTopic.content = self.request.get('content')
        newTopic.score = 0
       
        newTopic.put()
        self.redirect('/')
    
class Vote(webapp.RequestHandler):

    def post(self):
        topicDao = TopicDao()
        topic = topicDao.getTopic(self.request.get('content'))
           
        topic[0].score += 1
        topic[0].put()
        self.redirect('/')
        
class RestVote(webapp.RequestHandler):

    def get(self):
        topicDao = TopicDao()
        topic = topicDao.getTopicWithKey(self.request.get('key'))
           
        topic[0].score += 1
        topic[0].put()
        self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/addTopic', AddTopic),
                                      ('/vote', Vote),
                                      ('/admin', AdminPage),
                                      ('/deleteTopic', DeleteTopic),
                                      ('/editTopicAction', EditTopicPage),
                                      ('/api/vote', RestVote),
                                      ('/api/addTopic', RestAddTopic),
                                      ('/resturl', RestUrlPage),
                                      ('/performEdit', PerformEdit)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()